const bParser = require("@babel/parser");
const generator = require("@babel/generator");
const t = require("@babel/types");
const traverse = require("@babel/traverse").default;

const zcss = require('./zcss');
const zjs = require('./zjs');
const zhtm = require('./zhtm');
const { comOptsMap } = require("./zvuedata");

function transCEfuncs(script) {
    let ast = bParser.parse(script, {sourceType: "unambiguous"});

    traverse(ast, {
        enter(path) {
            if (t.isCallExpression(path.node)) {
                // console.log(path.node);
                // if (path.node.callee.name === "类型") {
                //     path.replaceWith(t.unaryExpression('typeof', path.node.arguments[0]));
                // }
                switch (path.node.callee.name) {
                    case '中翻英_html':
                        let str = path.node.arguments[0].value;
                        str = zhtm.transpile(str);
                        path.replaceWith(t.stringLiteral(str));
                        break;
                    
                    case '中翻英_css':
                        let sty = path.node.arguments[0].value;
                        sty = zcss.transpile("{" + sty + "}").slice(1, -1);
                        sty = sty.charAt(sty.length - 1) === ';' ? sty : sty + ';';
                        path.replaceWith(t.stringLiteral(sty));
                        break;

                    case '中翻英_js':
                        let js = path.node.arguments[0].value;
                        js = zjs.transpile(js);
                        path.replaceWith(t.stringLiteral(js));
                        break;

                    case '注册组件': // 代码重复
                        let obj = path.node.arguments[0];
                        for (prop of obj.properties) {
                            if (prop.key && prop.key.name) {
                                prop.key.name = comOptsMap[prop.key.name] || prop.key.name;
                            }
                        }
                        path.replaceWith(t.objectExpression(obj.properties))
                        break;
                
                    default:
                        break;
                }
            }
        }
    });

    let options = {
        // concise: true,
        retainLines: true,
        jsescOption: {minimal: true}
    }
    const output = new generator.CodeGenerator(ast, options, script).generate();
    // console.log(output.code);
    return output.code;
}

module.exports = {
    transCEfuncs
}